<?php
class sfPHPWord_Template extends PHPWord_Template
{
    /**
     * Document XML
     * 
     * @var string
     */
    private $_documentXML;
    
    /**
     * Create a new Template Object
     * 
     * @param string $strFilename
     */
    public function __construct($strFilename) {
        $path = dirname($strFilename);
        $this->_tempFileName = $path.DIRECTORY_SEPARATOR.time().'.docx';
        
        copy($strFilename, $this->_tempFileName); // Copy the source File to the temp File

        $this->_objZip = new ZipArchive();
        $this->_objZip->open($this->_tempFileName);
        
        $this->_documentXML = $this->_objZip->getFromName('word/document.xml');
    }    

    
    /**
     * Save Template
     * 
     * @param string $strFilename
     */
    public function save($strFilename) {
        if(file_exists($strFilename)) {
            unlink($strFilename);
        }
        
        $this->_objZip->addFromString('word/document.xml', $this->_documentXML);
        
        // Close zip file
        if($this->_objZip->close() === false) {
            throw new Exception('Could not close zip file.');
        }
        
        rename($this->_tempFileName, $strFilename);
    }
    
    /**
     * Set a Template value
     * 
     * @param mixed $search
     * @param mixed $replace
     */
    public function setValue($search, $replace) {
        if(substr($search, 0, 2) !== '[' && substr($search, -1) !== ']') {
            $search = '['.$search.']';
        }
        
        if(!is_array($replace)) {
            $replace = utf8_encode($replace);
        }
        
        $this->_documentXML = str_replace($search, $replace, $this->_documentXML);
    }    
    
    public function getExpressions(){
		$matches = array();
   		$pattern = '#\{[a-zA-Z0-9<>/]{1,}\}#';
   		$pattern = '#\${#';
		$matches = preg_split($pattern, $this->_documentXML, 0);
		//preg_match_all( $pattern , $this->_documentXML, $matches);
		unset($matches[0]);
		$expressions = array();
		foreach($matches as $expression){
			$finalPos = strpos($expression,'}',0);
			$stringOri = substr($expression,0,$finalPos);
			$expressions[] = $stringOri;
		}
		return $expressions;
	}
    
	
}